package com.boc.langxiang.presenter.common;


import com.boc.langxiang.contract.common.AddressManage2Contract;
import com.boc.langxiang.entity.events.AddAddressSuccessEvent;
import com.boc.langxiang.entity.request.AddAddressRequest;
import com.boc.langxiang.entity.request.EditAddressRequest;
import com.boc.langxiang.entity.response.AddAddressContent;
import com.boc.langxiang.entity.response.BaseResponse;
import com.boc.langxiang.net.ApiService;
import com.boc.langxiang.net.HandleErrorSubscriber;
import com.boc.langxiang.net.NetClient;

import org.greenrobot.eventbus.EventBus;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * CreateTime: 2016-06-14上午10:40
 * Author: wjkjinke00@126.com
 * Description:
 */
public class AddressManage2Presenter implements AddressManage2Contract.Presenter {

    private final ApiService mService;
    private AddressManage2Contract.View mView;

    public AddressManage2Presenter(AddressManage2Contract.View view) {
        mService = NetClient.getInstance().net().create(ApiService.class);
        mView = view;
    }

    @Override
    public void addAddress(AddAddressRequest request) {
        mView.showLoading();
        Observable<BaseResponse<AddAddressContent>> register = mService.createAddress(request.params());
        register.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new HandleErrorSubscriber<BaseResponse<AddAddressContent>>(mView) {
                    @Override
                    public void onSuccess(BaseResponse<AddAddressContent> response) {
                        AddAddressSuccessEvent event = new AddAddressSuccessEvent();
                        event.setAddressEntity(response.getContent().getAddrInfo());
                        EventBus.getDefault().post(event);
                        mView.addAddressSuccess();
                    }
                });
    }

    @Override
    public void editAddress(EditAddressRequest request ) {
        mView.showLoading();
        Observable<BaseResponse> register = mService.editAddress(request.params());
        register.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new HandleErrorSubscriber<BaseResponse>(mView) {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        AddAddressSuccessEvent event = new AddAddressSuccessEvent();
                        EventBus.getDefault().post(event);
                        mView.editAddressSuccess();
                    }
                });
    }
}
